import global from './global.js'
import drawQrcode  from './qrcode.esm'
// padstart兼容处理
if (!String.prototype.padStart) {
    String.prototype.padStart = function padStart(targetLength, padString) {
        targetLength = targetLength >> 0 // floor if number or convert non-number to 0;
        padString = String(typeof padString !== 'undefined' ? padString : ' ')
        if (this.length > targetLength) {
            return String(this)
        } else {
            targetLength = targetLength - this.length
            if (targetLength > padString.length) {
                padString += padString.repeat(targetLength / padString.length) // append to original to ensure we are longer than needed
            }
            return padString.slice(0, targetLength) + String(this)
        }
    }
}


/**
 * 简单确认框
 * @param {string} cont 提示文字
 * @returns {Promise<void>}
 */
export function confirm(cont, params={}) {
    return new Promise((reslove, reject) => {
        wx.showModal({
            title: '提示',
            content: cont,
            ...params,
            success: (res) => {
                if (res.confirm)
                    reslove()
                if (res.cancel)
                    reject()
            },
            fail: () => {
                reject()
            }
        })
    })
}

/**
 * 简单提示框，只有确认
 * @param {string} cont 提示文字
 * @returns {Promise<void>}
 */
export function alert(cont) {
    return new Promise((reslove) => {
        wx.showModal({
            title: '提示',
            content: cont,
            showCancel: false,
            success: () => {
                reslove()
            }
        })
    })
}

/**
 * 提示
 * @param {string} cont 提示文字
 * @param {'none'|'success'|'loading'} type 提示类型
 * @returns {Promise<void>}
 */
export function toast(cont, type = 'none', duration = 1500) {
    console.log(type)
    setTimeout(() => {
        return wx.showToast({
            icon: type,
            title: cont,
            duration: duration
        })
    }, 300)
}

/** 判断有没有指定的时间格式 */
export function dateFormat(fmt, date) {
    let ret
    const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString(), // 秒
        's+': date.getMilliseconds().toString() // 毫秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    }
    for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }
    }
    return fmt
}

/**
 * Url转Base64
 * @param {string} url 需要转为base64的Url
 * @param {boolean} ishead 是否需要data:image的base64头
 * @returns {Promise<string>} 转换结果
 */
export function urlTobase64(url, ishead = false) {
    return new Promise((reslove) => {
        wx.request({
            url: url,
            responseType: 'arraybuffer', // 最关键的参数，设置返回的数据格式为arraybuffer
            success: res => {
                // 把arraybuffer转成base64
                let base64 = wx.arrayBufferToBase64(res.data)

                // 不加上这串字符，在页面无法显示的哦
                base64 = (ishead ? 'data:image/jpeg;base64,' : '') + base64

                // 打印出base64字符串，可复制到网页校验一下是否是你选择的原图片呢
                reslove(base64)
            }
        })
    })
}

// 本地文件转base64
export function wxfileTobase64(url, ishead = false) {
    console.log(url, 'util-url')
    return new Promise((reslove, reject) => {
        wx.getFileSystemManager().readFile({
            filePath: url, // 选择图片返回的相对路径
            encoding: 'base64', // 编码格式
            success: res => { // 成功的回调
                reslove((ishead ? 'data:image/jpeg;base64,' : '') + res.data)
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

// base64转本地文件 
export function base64ToWxfile(base64, fileName) {
    const path = wx.env.USER_DATA_PATH + '/' + fileName
    return new Promise((reslove, reject) => {
        wx.getFileSystemManager().writeFile({
            filePath: path,
            data: base64,
            encoding: 'base64',
            success: () => {
                reslove(path)
            },
            fail: (err) => {
                console.log(err)
                reject(err)
            }
        })
    })
}
// 简易双向绑定
export function inputchange(event, t) {
    t.setData({
        [event.currentTarget.dataset.model]: event.detail.value
    })
}

// 小程序更新
export function upVersion() {
    if (wx.canIUse('getUpdateManager')) { // 判断当前微信版本是否支持版本更新
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate(function (res) {
            if (res.hasUpdate) { // 请求完新版本信息的回调
                updateManager.onUpdateReady(function () {
                    wx.showModal({
                        title: '更新提示',
                        content: '新版本已经准备好，是否重启应用？',
                        success: function (res) {
                            if (res.confirm) { // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                updateManager.applyUpdate()
                            }
                        }
                    })
                })
                updateManager.onUpdateFailed(function () {
                    wx.showModal({ // 新的版本下载失败
                        title: '已经有新版本了哟~',
                        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
                    })
                })
            }
        })
    }
}

// 生成记录点击时间戳的闭包
export function Anit() {
    let antiTimeStamp = 0
    return (event) => {
        if (antiTimeStamp + 1000 < event.timeStamp || antiTimeStamp - 1000 > event.timeStamp || event.timeStamp === 0) {
            antiTimeStamp = event.timeStamp
            return true
        }
        return false
    }
}
export const anit = Anit()

// 防抖
export function Shake() {
    let timer = -1
    return function (obj, millisecond = 300) {
        clearTimeout(timer)
        timer = setTimeout(obj, millisecond)
    }
}
export const shake = Shake()
/**
 * @param {String} url, // 应用路径，用于跳转链接
 * @param {'navigateTo'|'redirectTo'} type, // 应用状态，用于提示
 * @param {'可用'|'建设中'|'维护中'|'下线'} status, // 应用状态，用于提示
 */
export function goApp(url, type = 'navigateTo', status = 0) {
    status = Number(status)
    const goto = () => {
        // 如果传的url是空的
        if (!url) {
            toast('应用维护中，请稍后再试')
            return 0
        }

        // 判断应用类型，不同类型做不同的跳转方法
        if (/^https?:\/\//.test(url)) { // H5应用
            if (type === 'redirectTo') {
                wx.redirectTo({
                    url: '/pages/web-view/web-view?path=' + encodeURIComponent(url)
                })
            } else {
                wx.navigateTo({
                    url: '/pages/web-view/web-view?path=' + encodeURIComponent(url)
                })
            }
        } else if (/^external:\/\//.test(url)) { // 外部应用   应用格式    external://appId/path
            url = url.split('external://')[1]
            const list = url.split('/')
            const appId = list.splice(0, 1).join()
            const path = '/' + list.join('/')
            wx.navigateToMiniProgram({
                appId: appId,
                path: path
            })
        } else if (/^applet::/.test(url)) { // 小程序内部路径    链接格式    applet::小程序路径       如 applet::/index/index
            console.log(url)
            url = url.split('applet::')[1]
            console.log(url)
            if (type === 'redirectTo') {
                wx.redirectTo({
                    url
                })
            } else {
                wx.navigateTo({
                    url,
                    events: {
                        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                        callbackOperation(data) {
                            console.log(data, 'datadata')
                            if(data.data === 'longInsurance') {
                                setTimeout(()=>{
                                    alert('您暂未开通雇主保，请联系您的客服专员开通后再试')
                                }, 700)
                            }else if(data.data === 'lnsurance') {
                                setTimeout(()=>{
                                    alert('您暂未开通日日保，请联系您的客服专员开通后再试')
                                }, 700)
                            }
                        }
                    }
                })
            }
        } else if (/^tab::/.test(url)) { // 小程序tab路径     链接格式    tab::小程序路径       如 tab::/index/index
            url = url.split('tab::')[1]
            wx.switchTab({
                url: url
            })
        }
    }
    if (global.env === 'release') {
        switch (status) {
            case 0:
                goto()
                break

            case 1:
                toast('应用建设中')
                break

            case 2:
                toast('应用维护中，请稍后再试')
                break

            case 3:
                toast('应用已下线')
        }
    } else {
        goto()
    }

}

/**
 * 跳转列表
 * @param {[{
 *   url: string
 *   type: 'navigateTo'|'redirectTo'
 *   time: number
 * }]} urls
 */
export function goAppList(urls) {
    if (urls.length) {
        goApp(urls[0].url, urls[0].type)
        setTimeout(() => {
            urls.splice(0, 1)
            goAppList(urls)
        }, urls[0].time || 0)
    }

}

/**
 * 增加日志
 * @param data {{
 *     platform: String,
 *     content: String
 * }}
 */
export function addLog(data) {
    if (global.env === 'release')
        wx.request({
            url: 'https://cloudcode.51zidan.com/api/log/',
            data: data,
            method: 'get'
        })
}
/**
 * 扫描周边ibeacon设备（该接口暂不使用）
 * @param { String | Null } beaconId 如果传则表示指定搜索该设备，不传则表示获取所有设备
 * @param { Boolean | Null } isLoading 是否添加搜索中界面
 */
export function scanfIBeacon(beaconId, isLoading) {
    return new Promise((resolve, reject) => {
        wx.startBeaconDiscovery({
            uuids: ['FDA50693-A4E2-4FB1-AFCF-C6EB07647825'] // 该UUID新设备已不适用
        }).then(() => {
            console.log('scanf start')
            if (isLoading)
                wx.showLoading({
                    title: '正在搜索',
                    mask: true,
                })
            let timer
            let time = 0
            let beacons = []
            const clear = () => {
                console.log('scanf stop')
                // 清除倒计时
                clearInterval(timer)
                // 停止监听beacon
                wx.offBeaconUpdate()
                wx.stopBeaconDiscovery()
                if (isLoading)
                    wx.hideLoading()
            }

            wx.onBeaconUpdate((res) => {
                console.log('scanf', res)
                // 寻找beaconId逻辑
                if (beaconId) {
                    res.beacons.forEach(item => {
                        const beaconId2 = item.major + item.minor
                        if (beaconId === beaconId2) {
                            resolve(item)
                            clear()
                        }
                    })
                }
                // 搜索身边所有beacon逻辑
                else {
                    beacons = res.beacons
                }
            })
            if (beaconId) {
                timer = setInterval(() => {
                    time += 1
                    if (time === 60) {
                        clear()
                        reject('未找到考勤机')
                    }
                }, 1000)
            } else { // 不搜索指定的beacon时，至少等待5秒才可以返回结果
                timer = setInterval(() => {
                    time += 1
                    if (time > 5 && beacons.length > 0) {
                        resolve(beacons)
                        clear()
                    }
                    if (time === 60) {
                        clear()
                        reject('未找到考勤机')
                    }
                }, 1000)
            }

        }, (err) => {
            console.log(err)
            switch (err.errCode) {
                case 11000:
                    reject('该设备或系统不支持')
                    break
                case 11001:
                    reject('蓝牙未打开，请打开蓝牙后重试')
                    break
                case 11002:
                    reject('GPS定位未打开，请打开定位后重试')
                    break
                default:
                    reject('硬件信息读取错误，请稍后再试')
            }
        })
    })
}

/**
 * 扫描周边ibeacon设备
 */
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('')
}
export function scanfBluetooth() {
    return new Promise((resolve, reject) => {
        console.log('初始化蓝牙设备')
        wx.openBluetoothAdapter().then(() => {
            const scanf = () => {
                wx.startBluetoothDevicesDiscovery({
                    powerLevel: 'high'
                }).then(() => {
                    const sbuInsert = (str, length) => {
                        let low = str.toUpperCase()
                        let reg = new RegExp('/w{1,' + length + '}', 'g')
                        let ma = low.match(reg)
                        return ma.join(':')
                    }
                    let timer
                    let time = 0
                    let devices = []
                    wx.onBluetoothDeviceFound(res => {
                        console.log('onBluetoothDeviceFound', res)
                        const list = res.devices.filter(item => {
                            if (item.serviceData && Object.keys(item.serviceData).length) {
                                return true
                            }
                            return false
                        }).map(item => {
                            const key = Object.keys(item.serviceData)[0]
                            const value = ab2hex(item.serviceData[key])
                            console.log(ab2hex(item.serviceData[key]))
                            if (item.name === 'lantun') { // 名称为蓝豚则是自定义打卡设备
                                const data = value.slice(0, 12)
                                return sbuInsert(data, 2)
                            } else { // 否则解析minor的值
                                const major = parseInt(value.slice(2, 6), 16)
                                const minor = parseInt(value.slice(6, 10), 16)
                                return major + '' + minor
                            }
                        })

                        if (list.length) {
                            devices.push(...list)
                        }
                    })
                    timer = setInterval(() => {
                        time += 1
                        if (time % 6 === 0 && devices.length) {
                            clearInterval(timer)
                            resolve(devices)
                            wx.stopBluetoothDevicesDiscovery()
                            wx.closeBluetoothAdapter()
                        }
                        if (time === 30) {
                            wx.getBluetoothDevices().then(res => {
                                console.log('getBluetoothDevices', res)
                                const devices = res.devices.filter(item => {
                                    if (item.serviceData && Object.keys(item.serviceData).length) {
                                        return true
                                    }
                                    return false
                                }).map(item => {
                                    const key = Object.keys(item.serviceData)[0]
                                    const value = ab2hex(item.serviceData[key])
                                    console.log(ab2hex(item.serviceData[key]))
                                    if (item.name === 'lantun') { // 名称为蓝豚则是自定义打卡设备
                                        const data = value.slice(0, 12)
                                        return sbuInsert(data, 2)
                                    } else { // 否则解析minor的值
                                        const major = parseInt(value.slice(2, 6), 16)
                                        const minor = parseInt(value.slice(6, 10), 16)
                                        return major + '' + minor
                                    }
                                })
                                if (devices.length) {
                                    resolve(devices)
                                } else {
                                    reject('未找到考勤机')
                                }
                                clearInterval(timer)
                                wx.stopBluetoothDevicesDiscovery()
                                wx.closeBluetoothAdapter()
                            })
                        }
                    }, 1000)
                }, err => {
                    reject(err.errMsg)
                })
            }
            wx.openBluetoothAdapter({
                mode: 'peripheral'
            }).then(res => {
                console.log(res)
                scanf()
            }, err => {
                console.log(err)
                scanf()
            })
        }, err => {
            console.log(err)
            switch (err.errCode) {
                case 10001:
                    reject('未打开蓝牙，请打开蓝牙后再试')
                    break
                case 10009:
                    reject('系统版本过低')
                    break
                default:
                    reject(err.errMsg)
            }
        })
    })
}

/**
 * 小程序打开文档
 * @param {string} url 文件URL
 * @param {string} fileName 显示的文件名称
 * @returns {Promise<void>}
 */

export function openDocument(url, fileName) {
    return new Promise((resolve, reject) => {
        const file = wx.env.USER_DATA_PATH + '/' + fileName
        wx.downloadFile({
            url,
            filePath: file,
            success: function (res) {
                console.log(res, '下载时的res')
                const documentPath = file
                wx.openDocument({
                    showMenu: true,
                    filePath: documentPath,
                    success(res) {
                        console.log(res, 'open打开时的res')
                        resolve(res)
                    },
                    fail: (rej) => {
                        console.log(rej, 'open打开时的rej')
                        reject(rej)
                    }
                })
            },
            fail: (rej) => {
                console.log(rej, '下载时的rej')
                reject(rej)
            },
        })
    })
}

/**
 * wait等待
 * @param {number} timeout
 * @returns
 */
export function wait(timeout = 1000) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout)
    })
}

/**
 * 获取用户选择的位置
 * @returns {Promise<>}
 */
export function getLocation(config = {
    type: 'gcj02'
}) {
    return new Promise((resolve, reject) => {
        const get = () => {
            config.success = (res) => {
                resolve(res)
            }
            config.fail = () => {
                wx.showModal({
                    title: '温馨提示',
                    content: '小程序将获取您的授权用来显示位置信息,进行打卡操作',
                    success: res => {
                        if (res.confirm) {
                            wx.openSetting({
                                success(res) {
                                    if (res.authSetting['scope.userLocation']) {
                                        get()
                                    } else {
                                        reject()
                                        toast('授权获取失败，无法打开，请确认后再试')
                                    }
                                }
                            })
                        }
                    }
                })
            }
            wx.getLocation(config)
        }
        get()
    })
}
// 身份证转年龄
export function getCardAge(identityCard) {
    let len = (identityCard + '').length
    if (len == 0) {
        return 0
    } else {
        if ((len != 15) && (len != 18)) // 身份证号码只能为15位或18位其它不合法
        {
            return 0
        }
    }
    let strBirthday = ''
    if (len == 18) // 处理18位的身份证号码从号码中得到生日和性别代码
    {
        strBirthday = identityCard.substr(6, 4) + '/' + identityCard.substr(10, 2) + '/' + identityCard.substr(12, 2)
    }
    if (len == 15) {
        strBirthday = '19' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2)
    }
    // 时间字符串里，必须是“/”
    let birthDate = new Date(strBirthday)
    let nowDateTime = new Date()
    let age = nowDateTime.getFullYear() - birthDate.getFullYear()
    // 再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
    if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
        age--
    }
    return age
}
// 通过身份证号判断性别
export function getGenderByIdNumber(idNumber) {
    if (idNumber) {
        let genderCode // 性别代码
        if (idNumber.length == 18) { // 二代身份证号码长度为18位（第17位为性别代码）
            genderCode = idNumber.charAt(16)
        } else if (idNumber.length == 15) { // 一代身份证号码长度为15位（第15位为性别代码）
            genderCode = idNumber.charAt(14)
        }
        if (genderCode && !isNaN(genderCode)) {
            // 两代身份证号码的性别代码都为男奇女偶
            if (parseInt(genderCode) % 2 == 0) {
                return '0'
            }
            return '1'
        }
    }
}

export function createQrcode(elId, content, qrCodeWidth = 300) {
    return new Promise((resolve, reject) => {
        const query = wx.createSelectorQuery()
        console.log(990, elId)
        query.select('#' + elId).fields({
            node: true,
            size: true
        }).exec((res) => {
            console.log(123, res)
            const canvas = res[0].node
            drawQrcode({
                canvas,
                width: qrCodeWidth,
                padding: 30,
                background: '#ffffff',
                foreground: '#000000',
                text: content
            })
            wx.canvasToTempFilePath({
                canvasId: elId,
                canvas,
                width: qrCodeWidth,
                height: qrCodeWidth,
                destWidth: qrCodeWidth,
                destHeight: qrCodeWidth,
                success(res) {
                    console.log(888, res.tempFilePath)
                    resolve(res.tempFilePath)
                },
                fail(err) {
                    reject(err)
                }
            })
        })
    })
}

export default {
    confirm,
    alert,
    toast,
    dateFormat
}